<?php

namespace backend\models;

use Yii;
use backend\models\GroupPermission;
/**
 * This is the model class for table "user_permission".
 *
 * @property integer $user_id
 * @property integer $permission_id
 */
class UserPermission extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'user_permission';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['user_id', 'permission_id'], 'required'],
            [['user_id', 'permission_id'], 'integer']
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels(){
        return [
            'user_id' => 'User ID',
            'permission_id' => 'Permission ID',
        ];
    }
    /*
     * create permission for user after create user
    */
    public function insertPermissionUserCreated($array){
        $fag= FALSE;
        $permission = GroupPermission::getArrayPermissionOfGroup(intval($array['GID']));
        if(count($permission)>0){
             foreach ($permission as $key=>$pre){
                 $mode = new UserPermission();
                 $mode->user_id=$array['UID'];
                 $mode->permission_id =$pre;               
                 $mode->save();
             }
             $fag=TRUE;
        }
        return $fag;
    }
    /*
     * add permission to user
     */
    public function addPermissionUser($array){
        $user_id = $array["UID"];
        $permission = $array['PER'];
        UserPermission::deleteAll("user_id=".$user_id);
        foreach ($permission as $key=>$pre){
            $mode = new UserPermission();
            $mode->user_id = $user_id;
            $mode->permission_id = $pre;
            $mode->save();
        }
        return TRUE;
    }
    /*
     * get all permission of user
     */
    public function getArrayOfUser($user_id){
        $data = [];
        $all_permission = UserPermission::find()
                ->select('permission_id')
                ->where('user_id='.$user_id)
                ->all();
        foreach ($all_permission as $pre){
            $data[]=$pre['permission_id'];
        }
        return $data;
    }
    
}
